#!/bin/bash

clear

datalogger_on=0

home_folder="/home/aqdms/CARBLog"

#REACTIVATE

#check to see if interface is already active
if [ "$(ps -fe | grep "\/bin\/bash .\/interface.sh" | wc -l)" -gt 2 ]; then
	echo "CARBLogger already running.  Now exiting."
	exit
fi

#Remove text editor backup files
rm -f resources/*_drv/.*~
rm -f resources/*_drv/*~
#CHECK FOR UNCONFIGURED DMS.CFG
if [ `(grep -v ^\# | wc -l )<sys_resources/dms.cfg` -eq 0 ]; then
	xmessage "CARBLogger has not been configured to report data to DMS"&
fi
#CHECK FOR UNCONFIGURED EMAIL
	

#Catch control-c and clean up testd instances if necessary
cleanup () {
	clear
	echo "Caught Signal.  Shutting Down Datalogger."
	if [ "$datalogger_on" -eq 1 ]; then
		d_shutdown
	fi
	exit 1
}

trap cleanup 1 2 3 6 15

#read config file
while read line; do
	eval $line
done < Config/config

#read and store the list or drivers
#list all folders in resources labelled *drv (shows available instruments)
drv_folders=$(ls resources | grep drv)

#Load driver folders into array
count_drv=1
for i in $drv_folders; do
	drv_list[$count_drv]="$i" #driver list array
	count_drv=`expr $count_drv + 1`
	max_count_drv="$count_drv"
done

#Create array of active/configured instruments from config file
count_act_inst=1
max_act_inst=0
for i in $active_inst; do
	act_inst_array[$count_act_inst]="$i"
	count_act_inst=`expr $count_act_inst + 1`
	max_act_inst="$count_act_inst"
done
#add two to max_act_inst to account for ingest manager and reporter
count_act_inst=`expr $count_act_inst + 2`
#flag for first time datalogger startup
first_time=0

#Find Available Serial Ports and populate spt_array with values
#MOVED THIS TO THE CONFIG FILE AND MODIFIED TO WORK WITH PERLE --MJV 
#serial_ports=$(ls /dev/ttyPS[0-7] && ls /dev/ttyS*)
spt_array_nav=1

for i in $serial_ports; do
	spt_array[$spt_array_nav]="$i" #Serial Port Array
	spt_array_nav=`expr $spt_array_nav + 1`
done
spt_array_max="$spt_array_nav"

###########################################################################################
#
#Function for temporarily adding backslashes to variables for display
#
###########################################################################################
add_backslash () {
	if [ "$1" = "log" ]; then
		DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
		echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
		echo "in backslash" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
	fi
	return_string=$(echo "$1" | sed s/\\\\/\\\\\\\\/g)
	echo "$return_string"
}

###########################################################################################
#
#Edit Parameter function
#called by Edit Instrument Function
#
###########################################################################################

edit_parameter () {
	if [ "$1" = "log" ]; then
		DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
		echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
		echo "in edit parameter" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
	fi
	array_nav=1
	#echo "$max_params"  ##DEBUG
	exist_flag=0
	while [ "$array_nav" -lt "$max_params" ]; do
		#echo "${param_name[$array_nav]}" ###DEBUG
		if [ "${param_name[$array_nav]}" = "$switch" ]; then
			new_in=0
			while [ "$new_in" -eq "0" ]; do
				clear
				name_error=0
				
				#################serial port display###########
				if [ "$serial_port_flag" -eq 1 ]; then
					echo "Choose from the following available serial ports"
					echo "Serial Port is currently set to ${param_value[$array_nav]}"
					echo "Press Enter to keep the current value"
					spt_counter=1
					spt_valid_counter=1 #navigate array of open serial ports
					while [ "$spt_counter" -lt "$spt_array_max" ]; do
						spt_array_counter=1 #counter for serial port array
						spt_disp_flag=0 #flag for menu display, 1 if serial port assigned, 0 if not. display on 0
						while [ "$spt_array_counter" -lt "$array_count_max" ]; do
							#echo "u_spt | ${u_spt_array[$spt_array_counter]} | spt_array | ${spt_array[$spt_counter]} " ##DEBUG
							#check to see if serial port is already assigned
							if [ "${u_spt_array[$spt_array_counter]}" = "${spt_array[$spt_counter]}" ]; then
								spt_disp_flag=1
							fi
							spt_array_counter=`expr $spt_array_counter + 1`
						done
						#generate serial port menu for user
						if [ "$spt_disp_flag" -eq 0 ]; then
							spt_valid[$spt_valid_counter]="$spt_counter" #array to store spt_array location of open serial port
							echo "$spt_valid_counter. ${spt_array[$spt_counter]}"
							spt_valid_counter=`expr $spt_valid_counter + 1`
						fi
						spt_counter=`expr $spt_counter + 1`
					done
					spt_valid_max="$spt_valid_counter" #max value of the spt_valid array
					echo -n ":>"
					non_int_flag=0
					read usr_input
					#check for non numeric user input#
					echo $usr_input | grep "[^0-9]" > /dev/null 2>&1
					if [ "$?" -eq "0" ]; then
						non_int_flag=1
						echo "Invalid Input"
						exist_flag=1
						error_flag=1
						sleep 1
					fi
					#check for blank user input
					if [ "$usr_input" = "" ]; then
						spt_array_counter=1
						spt_flag=0 #flag to indicate an assigned serial port overlap
						while [ "$spt_array_counter" -lt "$array_count_max" ]; do
							#compare used serial port array with the assigned serial port
							if [ "${u_spt_array[$spt_array_counter]}" = "${param_value[$array_nav]}" ]; then
								spt_flag=1
								#echo "matching port = ${u_spt_array[$spt_array_counter]} set port = ${param_value[$array_nav]}" ##DEBUG
							fi
							spt_array_counter=`expr $spt_array_counter + 1`
						done
						if [ "$spt_flag" -eq 1 ] && [ "$edit_flag" -eq 0 ]; then
							echo "Serial Port Already Assigned.  Please Select Another."
							error_flag=1
							exist_flag=1
							non_int_flag=1
							sleep 1
						else
							echo "Serial Port will remain ${param_value[$array_nav]}"
							new_in=1
							exist_flag=1
							sleep 1
							non_int_flag=1
						fi
					fi
					if [ "$non_int_flag" -eq 0 ]; then
						if [ "$usr_input" -ge "$spt_valid_max" ] || [ "$usr_input" -eq 0 ]; then
							echo "Invalid Input"
							error_flag=1
							exist_flag=1
							sleep 1
						else
							spt_array_counter=1
							spt_flag=0
							while [ "$spt_array_counter" -lt "$array_count_max" ]; do
								if [ "${u_spt_array[$spt_array_counter]}" = "${spt_array[${spt_valid[$usr_input]}]}" ]; then
									spt_flag=1
									#echo "used spt array val = ${u_spt_array[$spt_array_counter]} spt_array val = ${spt_array[${spt_valid[$usr_input]}" ##DEBUG
								fi
								spt_array_counter=`expr $spt_array_counter + 1`
							done
							if [ "$spt_flag" -eq 1 ]; then
								echo "Invalid Input"
								error_flag=1
								exist_flag=1
								sleep 1
							else
								echo "Set Serial Port to ${spt_array[${spt_valid[$usr_input]}]}?"
								echo -n ":>"
								read y_or_no
								if [ "$y_or_no" = "y" ]; then
									param_value[$array_nav]="${spt_array[${spt_valid[$usr_input]}]}"
									new_in=1
									echo "$parameter_name changed to ${param_value[$array_nav]}"
									exist_flag=1
									sleep 1
								else
									:
								fi
							fi
						fi
					fi
				#################End Serial Port Display######################	
				else
					echo "$parameter_name is currently set to ${param_value[$array_nav]}"
					echo -n "Enter New Value (Press enter for no change):>"
					read -r usr_input
					if [ "$usr_input" = "" ]; then
						echo "Change $parameter_name to $(add_backslash "${param_value[$array_nav]}") (y/n)?"
						read y_or_no
						if [ "$y_or_no" = "y" ]; then
							#echo "in first yes" ##DEBUG
							if [ "$change_name_flag" -eq 1 ] && [ "$edit_flag" -eq 0 ]; then
								n_check_counter=1
								while [ "$n_check_counter" -lt "$array_count_max" ]; do
									#echo "in name check loop | n check | $n_check_counter | $array_count_max " ##DEGBUG
									if [ "${d_name_array[$n_check_counter]}" = "${param_value[$array_nav]}" ]; then
										name_error=1
									fi
									n_check_counter=`expr $n_check_counter + 1`
								done
							fi
							if [ "$name_error" -eq 1 ] && [ "$edit_flag" -eq 0 ]; then
								echo "Name already used.  Re-enter name"
								sleep 1
							else
								param_value[$array_nav]="${param_value[$array_nav]}"
								new_in=1
								echo "$parameter_name changed to ${param_value[$array_nav]}"
								exist_flag=1
								sleep 1
							fi
						else
							:
						fi
					else
						echo "Change $parameter_name to $usr_input (y/n)?"
						read y_or_no
						if [ "$y_or_no" = "y" ]; then
							if [ "$change_name_flag" -eq 1 ] && [ "$edit_flag" -eq 0 ]; then
								n_check_counter=1
								#echo "loop 1 " ##debug
								#echo " n check | $n_check_counter array | $array_count_max"##debug
								while [ "$n_check_counter" -lt "$array_count_max" ]; do
									#echo "d name | ${d_name_array[$n_check_counter]} | param | ${param_value[$array_nav]}" ## debug
									if [ "${d_name_array[$n_check_counter]}" = "$usr_input" ]; then
										name_error=1
									fi
									n_check_counter=`expr $n_check_counter + 1`
								done
							fi
							if [ "$name_error" -eq 1 ] && [ "$edit_flag" -eq 0 ]; then
								echo "Name already used.  Re-enter name"
								sleep 1
							else
								param_value[$array_nav]="$usr_input"
								new_in=1
								echo "$parameter_name changed to ${param_value[$array_nav]}"
								exist_flag=1
								sleep 1
							fi
						else
							:
						fi
					fi
				fi
			done
			array_nav=`expr $array_nav + 1`
		else
			array_nav=`expr $array_nav + 1`
		fi
	done
	if [ "$exist_flag" -eq 0 ]; then
		clear
		echo "$parameter_name Not Found.  Create $parameter_name? (y/n)"
		echo -n ":>"
		read usr_input
		if [ "$usr_input" = "y" ]; then
			echo -n "Enter New Value:>"
			read usr_input
			echo "Change $parameter_name to $usr_input (y/n)?"
			read y_or_no
			if [ "$y_or_no" = "y" ]; then
				max_n_value=`expr $max_n_value + 1`
				max_p_value=`expr $max_p_value + 1`
				n_array_nav="$max_n_value"
				p_array_nav="$max_p_value"
				param_name[$n_array_nav]="$switch"
				param_value[$p_array_nav]="$usr_input"
				echo "$parameter_name changed to ${param_value[$p_array_nav]}"
				sleep 1
			else
				:
			fi
		elif [ "$usr_input" = "n" ]; then
			echo "returning to main menu without saving"
		fi
	fi
}



###########################################################################################
#
#Edit Instrument Function
#
###########################################################################################

edit_instrument () {
	if [ "$1" = "log" ]; then
		DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
		echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
		echo "in edit instrument" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
	fi
	
	save_flag=0
	param_count=1
	max_params=1
	odd_counter=1
	temp_p_count=1
	for i in $param; do
		temp_p[$temp_p_count]="$i"
		temp_p_count=`expr $temp_p_count + 1`
	done
	
#echo "$param"  ##DEBUG###
	
	max_p_count="$temp_p_count"
	temp_p_count=1
	p_name_count=1
	p_value_count=1
	quote_count=`echo "$param" | grep -o "[\"“”]" | wc -l`
	q_counter=0
	
	#echo "quote_count $quote_count"  ###DEBUG####
	#echo "max_p_count $max_p_count" ###DEBUG###
	
	while [ "$temp_p_count" -lt "$max_p_count" ]; do
	   	###############################
		##handler for command strings##
		###############################
		if [ "${temp_p[$temp_p_count]}" = "-c" ]; then
			#echo "in -c loop :: temp_p = ${temp_p[temp_p_count]}"   ### DEBUG####
			param_name[$p_name_count]="${temp_p[temp_p_count]}"
			#echo "param_name ${param_name[p_name_count]}"  ###DEBUG###
			p_name_count=`expr $p_name_count + 1`
			temp_p_count=`expr $temp_p_count + 1`
			q_count_temp=`echo "${temp_p[$temp_p_count]}" | grep -o "[\"“”]" | wc -l`
			q_counter=`expr $q_counter + $q_count_temp`
			temp_command="${temp_p[$temp_p_count]}"
		
			#echo "p_name_c : $p_name_count | temp_p_count : $temp_p_count | q_counter : $q_counter | q_count_temp : $q_count_temp" ##DBUG
			#echo "temp_command : $temp_command" ##DEBUG
		
			while [ "$q_counter" -lt "$quote_count" ]; do
				#echo "in -c loop, command append" ##DEBUG##
				temp_p_count=`expr $temp_p_count + 1`
				q_count_temp=`echo "${temp_p[$temp_p_count]}" | grep -o "[\"“”]" | wc -l`
				q_counter=`expr $q_counter + $q_count_temp`
				temp_command="$temp_command ${temp_p[$temp_p_count]}"
				#echo "p_name_c : $p_name_count | temp_p_count : $temp_p_count | q_counter : $q_counter | q_count_temp : $q_count_temp" ##DBUG
				#echo "temp_command : $temp_command" ##DEBUG
			done
			#echo "completed command append" ##DEBUG		
			param_value[$p_value_count]="$temp_command"
			#echo "param_value : ${param_value[p_value_count]}"  ##DEBUG
			p_value_count=`expr $p_value_count + 1`
			temp_p_count=`expr $temp_p_count + 1`
			#echo "p_value_count : $p_value_count"  ##DEBUG##  
		fi
	
		test_p="${temp_p[$temp_p_count]:0:1}"
		if [ "$test_p" = "-" ]; then
			#echo "in - loop"  ##DEBUG
			param_name[$p_name_count]="${temp_p[temp_p_count]}"
			#echo "param_name : ${param_name[p_name_count]}"  ## DEBUG ##
			p_name_count=`expr $p_name_count + 1`
			advance_p_count=`expr $temp_p_count + 1`
			test_p="${temp_p[$advance_p_count]:0:1}"
			#echo "p_name_c : $p_name_count | temp_p_count : $temp_p_count | advance_p_count : $advance_p_count" ##DBUG
			#echo "test_p : $test_p"  ##DEBUG
			if [ "test_p" = "-" ]; then
				#echo "in second - loop"  ##DEBUG
				param_value[$p_value_count]=""
				#echo "param_value : ${param_value[$p_value_count]}" ##DEBUG
				p_value_count=`expr $p_value_count + 1`
				#echo "p_value_count : $p_value_count"  ##DEBUG
			fi
		elif [ `echo "${temp_p[$temp_p_count]}" | grep -o "\"" | wc -l` -eq 0 ]; then
			#echo " in elif 0 quote"  ##DEBUG
			param_value[$p_value_count]="${temp_p[temp_p_count]}"
			#echo "par_value : ${param_value[$p_value_count]}"   ##DEBUG
			p_value_count=`expr $p_value_count + 1`
			#echo "pvalue count : $p_value_count"  ##DEBUG
		elif [ `echo "${temp_p[$temp_p_count]}" | grep -o "\"" | wc -l` -eq 2 ]; then
			#echo " in elif 2 quote"  ##DEBUG
			param_value[$p_value_count]="${temp_p[temp_p_count]}"
			#echo "par_value : ${param_value[$p_value_count]}"   ##DEBUG
			p_value_count=`expr $p_value_count + 1`
			#echo "pvalue count : $p_value_count"  ##DEBUG
		elif [ `echo "${temp_p[$temp_p_count]}" | grep -o "\"" | wc -l` -eq 1 ]; then
			#echo "in elif 1 quote"  ##DEBUG
			temp_value="${temp_p[temp_p_count]}"
			#echo "initial temp value : $temp_value"  ##DEBUG
			flag=0
			while [ "$flag" -eq 0 ]; do
				advance_p_count=`expr $temp_p_count + 1`
				if [ `echo "${temp_p[$advance_p_count]}" | grep -o "\"" | wc -l` -eq 0 ]; then
		  			#echo "in elif 1 quote 2nd loop eq 0"  ##DEBUG
					temp_value="$temp_value ${temp_p[$advance_p_count]}"
					#echo "temp value : $temp_value"  ##DEBUG
					temp_p_count=`expr $temp_p_count + 1`
					#echo "temp p count : $temp_p_count" ##DEBUG
				elif [ `echo "${temp_p[$advance_p_count]}" | grep -o "\"" | wc -l` -gt 0 ]; then
					#echo "in elif 1 quote 2nd loop gt 0" ##DEBUG
					temp_value="$temp_value ${temp_p[$advance_p_count]}"
					temp_p_count=`expr $temp_p_count + 1`
					flag=1
				fi
			done
			param_value[$p_value_count]="$temp_value"
			#echo "param value final : ${param_value[$p_value_count]}"  ##DEBUG
			p_value_count=`expr $p_value_count + 1`
		fi
		temp_p_count=`expr $temp_p_count + 1`
		#echo "finished loop"  ##DEBUG7
	done
	max_p_value="$p_value_count"
	max_n_value="$p_name_count"
	max_params="$p_name_count"
	main_menu_flag=0
	while [ "$main_menu_flag" -eq "0" ]; do
		clear
		n_flag=0
		spt_flag=0
		save_error=0
		ordered_counter=0
		ordered_param_n=( -r -d -b -c -w -l -p -t -C -m -U -L -n -F -T -o -2 -f -R -E)
		#echo "$ordered_param_n"  #####DEBUG
		tempc=0
		while [ "$ordered_counter" -lt 20 ]; do #create ordered array of values for display in menu (1=r,2=d,3=b,4=c,5=w,6=l,7=f,8=p,9=t,10=C)
			found_flag=0
			array_counter=1
			while [ "$array_counter" -lt "$max_params" ]; do
				if [ "${ordered_param_n[$ordered_counter]}" = "${param_name[$array_counter]}" ]; then
					ordered_param_v[$ordered_counter]="${param_value[$array_counter]}"
					array_counter=`expr $array_counter + 1`
					found_flag=1
				else
					array_counter=`expr $array_counter + 1`
				fi
			done
			if [ "$found_flag" -eq 0 ]; then
				ordered_param_v[$ordered_counter]=""
			fi
			ordered_counter=`expr $ordered_counter + 1`
		done
		serial_port_flag=0
		change_name_flag=0
		param_count=1
		echo "Select Parameter to Edit for $inst_name (Current Parameter Settings are Shown)"
	
		if [ "${ordered_param_v[0]}" != "" ]; then
			echo "r.  Channel Name (${ordered_param_v[0]})"
		fi
	
		if [ "${ordered_param_v[1]}" != "" ]; then
			echo "d.  Serial Port (${ordered_param_v[1]})"
		fi
	
		if [ "${ordered_param_v[2]}" != "" ]; then
			echo "b.  Baud Rate (${ordered_param_v[2]})"
		fi
	
		if [ "${ordered_param_v[3]}" != "" ]; then
			echo "c.  Command String (${ordered_param_v[3]})"
		fi
	
		if [ "${ordered_param_v[4]}" != "" ]; then
			echo "w.  Response Wait Time (${ordered_param_v[4]})"
		fi
	
		if [ "${ordered_param_v[5]}" != "" ]; then
			echo "l.  Response String Length (${ordered_param_v[5]})"
		fi
	
		if [ "${ordered_param_v[6]}" != "" ]; then
			echo "p.  8 bit, no parity, 1 stop bit (${ordered_param_v[6]})"
		fi
	
		if [ "${ordered_param_v[7]}" != "" ]; then
			echo "t.  Data Terminal Ready (${ordered_param_v[7]})"
		fi
	
		if [ "${ordered_param_v[8]}" != "" ]; then
			echo "C.  CTR (${ordered_param_v[8]})"
		fi
	
		if [ "${ordered_param_v[14]}" != "" ]; then 
			echo "T.  Separate Time Serial Port (${ordered_param_v[14]})"
		fi
	
		if [ -e ./resources/$inst_name/.hourly ] && [ "${ordered_param_v[9]}" != "" ]; then
			echo "m.  Two Digit Minute To Run Each Hour (${ordered_param_v[9]})"
		fi
	
		if [ "${ordered_param_v[10]}" != "" ]; then
			echo "U.  Upper Flow Alerting Limit (${ordered_param_v[10]})"
		fi
	
		if [ "${ordered_param_v[11]}" != "" ]; then
			echo "L.  Lower Flow Alerting Limit (${ordered_param_v[11]})"
		fi
	
		if [ "${ordered_param_v[12]}" != "" ]; then
			echo "n.  Instrument Name (${ordered_param_v[12]})"
		fi
	
		if [ "${ordered_param_v[13]}" != "" ]; then
			echo "F.  Flow Rate Set Point (${ordered_param_v[13]})"
		fi

		if [ "${ordered_param_v[15]}" != "" ]; then 
			echo "o.  Occurrence code [use with co-location] (${ordered_param_v[15]})"
		fi
	
		if [ "${ordered_param_v[16]}" != "" ]; then 
			echo -e "2.  BAM Firmware Version, \"on\" for ver.2, \"off\" for ver. 3  (${ordered_param_v[16]})"
		fi	
		
		if [ "${ordered_param_v[17]}" != "" ]; then 
			echo -e "f.  Enter 50 for QTOT value of 0.824 and 42 for QTOT value of 0.700 (${ordered_param_v[17]})"
		fi
		if [ "${ordered_param_v[18]}" != "" ]; then 
			echo -e "R.  Recovery time (${ordered_param_v[18]})"
		fi
	
		if [ "${ordered_param_v[19]}" != "" ]; then 
			echo -e "E.  Equilibration time (${ordered_param_v[19]})"
		fi
	
		echo "q.  Return To Main Menu Without Saving"
		echo "s.  Save Settings"
		echo -n ":>"
		read usr_input
		
		case "$usr_input" in

			"r")
				switch="-r"
				parameter_name="Channel Name"
				change_name_flag=1
				edit_parameter
			;;
			"d")
				switch="-d"
				parameter_name="Serial Port"
				serial_port_flag=1
				edit_parameter
			;;
			"b")
				switch="-b"
				parameter_name="Baud Rate"
				edit_parameter
			;;
			"c")
				switch="-c"
				parameter_name="Command String"
				edit_parameter
			;;
			"w")
				switch="-w"
				parameter_name="Response Wait Time"
				edit_parameter
			;;
			"l")
				switch="-l"
				parameter_name="Response String Length"
				edit_parameter
			;;
			"p")
				switch="-p"
				parameter_name="8N1 (8 bit, no parity, 1 stop bit)"
				edit_parameter
			;;
			"t")
				switch="-t"
				parameter_name="DTR"
				edit_parameter
			;;
			"C")
				switch="-C"
				parameter_name="CTR"
				edit_parameter
			;;
			"m")
				if [ -e ./resources/$inst_name/.hourly ]; then
					switch="-m"
					parameter_name="min"
					edit_parameter
				else 
					echo "invalid input"
					sleep 1
				fi
			;;
			"U")
				switch="-U"
				parameter_name="UpperLimit"
				edit_parameter
			;;
			"L")
				switch="-L"
				parameter_name="LowerLimit"
				edit_parameter
			;;
			"n")
				switch="-n"
				parameter_name="Instrument Name"
				edit_parameter
			;;
			"T")
				switch="-T"
				parameter_name="TimePort"
				serial_port_flag=1
				edit_parameter
			;;
			"F")
				switch="-F"
				parameter_name="Flow Rate Set Point"
				edit_parameter
			;;
			"q" )
				main_menu_flag=1
			;;
			"o") 
				switch="-o"
				parameter_name="occurrence"
				edit_parameter
			;;
			"2") 
				switch="-2"
				parameter_name="BAM Firmware Version"
				edit_parameter
			;;
			"f")
				switch="-f"
				parameter_name="BAM Sample Time"
				edit_parameter
			;;
			"R")
				switch="-R"
				parameter_name="Recovery Time"
				edit_parameter
			;;
			"E")
				switch="-E"
				parameter_name="Equilibration Time"
				edit_parameter
			;;
			"s" )
				main_menu_flag=1
				save_flag=1
			;;
			* )
				echo "Not a valid option"
				sleep 1
			;;	
		esac
		#done
		
		#echo "${drv_list[$instrument]}"
		if [ "$save_flag" -eq 1 ]; then
			name_cell=0
			spt_cell_1=0
			spt_cell_2=0
	  		#find Serial port and Name array cells
			array_nav=1
			while [ "$array_nav" -lt "$max_params" ]; do
				#echo "In find cell  loop" ## DEBUG
				if [ "${param_name[$array_nav]}" = "-d" ]; then
					spt_cell_1="$array_nav"
				#echo "spt cell port" ## DEBUG
				fi
				if [ "${param_name[$array_nav]}" = "-r" ]; then
					name_cell="$array_nav"
					#echo "flagging name" ##debug
				fi
				if [ "${param_name[$array_nav]}" = "-T" ]; then
					spt_cell_2="$array_nav"
					#echo "spt cell port" ## DEBUG
				fi
				array_nav=`expr $array_nav + 1`
			done

			#check name and serial ports against already assigned names and ports
			spt_array_counter=1
			while [ "$spt_array_counter" -lt "$array_count_max" ]; do
				#echo "in check loop | $spt_array_counter" ##debug
				#echo "u_spt ${u_spt_array[$spt_array_counter]} | param_val ${param_value[$spt_cell]}" ##debug
				if [ -n "${u_spt_array[$spt_array_counter]}" ]; then
					if [ "${u_spt_array[$spt_array_counter]}" = "${param_value[$spt_cell_1]}" ] || [ "${u_spt_array[$spt_array_counter]}" = "${param_value[$spt_cell_2]}" ]; then
						#echo "flagging spt"  ## debug
						spt_flag=1
					fi
				fi
				#echo "${d_name_array[$spt_array_counter]} | ${param_value[$spt_cell]}"  ##debug
				if [ "${d_name_array[$spt_array_counter]}" = "${param_value[$name_cell]}" ]; then
				#echo "flagging name" ## debug
					n_flag=1
				fi		
				spt_array_counter=`expr $spt_array_counter + 1`
			done
		
		
			if [ "$spt_flag" -eq 1 ] || [ "$n_flag" -eq 1 ] && [ "$edit_flag" -eq 0 ]; then
				if [ "$spt_flag" -eq 1 ]; then
					echo "Serial Port already assigned.  Please assign to an unused port."
					save_error=1
					sleep 2
				fi
				if [ "$n_flag" -eq 1 ]; then
					echo "Instrument Name already used.  Please rename instrument."
					save_error=1
					sleep 1
				fi
				read -p "Press Any Key To Continue" -n 1 -s
			else
				#echo "$inst_name | $config_id" ##DEBUG 
				array_nav=1
				echo -n "${param_name[$array_nav]} ${param_value[$array_nav]} " >./resources/$inst_name/.usr$config_id
				array_nav=2
				while [ "$array_nav" -lt "$max_n_value" ]; do
					echo -n "${param_name[$array_nav]} ${param_value[$array_nav]} " >>./resources/$inst_name/.usr$config_id
					array_nav=`expr $array_nav + 1`
				done
				#TO DO add check for disabled instrument
				echo "0" > ./resources/$inst_name/.disabled$config_id
				echo "Saving Settings"
				sleep 1
			fi
		fi

		if [ "$save_flag" -eq 1 ] && [ "$edit_flag" -eq 0 ] && [ "$config_id" -eq 1 ] && [ "$save_error" -eq 0 ]; then
			act_inst_count=1
			exist_flag=0
			if [ "$max_act_inst" -eq 0 ]; then
				#echo "$inst_name"
				act_inst_array["$act_inst_count"]="$inst_name"
				max_act_inst=`expr $max_act_inst + 2`
				act_inst_temp=""
				act_inst_temp="${act_inst_array[$act_inst_count]}"
			else
				if [ "$exist_flag" -eq 0 ]
					act_inst_count="$max_act_inst"
				then
					act_inst_array["$act_inst_count"]="$inst_name"
					max_act_inst=`expr $max_act_inst + 1`
				fi
		
				####Create new act_inst parameter in config###
				act_inst_count=1
				act_inst_temp=""
				while [ "$act_inst_count" -lt "$max_act_inst" ]; do
					if [ "$act_inst_count" -eq 1 ]; then
						act_inst_temp="${act_inst_array[$act_inst_count]}"
						act_inst_count=`expr $act_inst_count + 1`
					else
						act_inst_temp="$act_inst_temp ${act_inst_array[$act_inst_count]}"
						act_inst_count=`expr $act_inst_count + 1`
					fi
				done	
			fi
		
			active_inst="$act_inst_temp"
			sed --e 's/\(active_inst=\).*/\1\"'"$active_inst"'\"/' <./Config/config>./Config/config.tmp
			cp ./Config/config.tmp ./Config/config
			echo "Saving Config"
			sleep 1
		fi
	done
}

####################################################################################################
#
#Shutdown Datalogger Function
#
####################################################################################################

d_shutdown () {
	if [ "$1" = "log" ]; then
		DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
		echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
		echo "in shutdown" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
	fi
	clear
	
	if [ "$datalogger_on" -eq 1 ]; then
		echo "Stop Datalogger"
		echo "shutting down active instruments"
		count_proc_id=1
		while [ "$count_proc_id" -lt "$max_proc_id" ]; do
			#echo "${proc_id_array[$count_proc_id]}"  ## DEBUG
			#check PID array value to see if it contains seed value, if so, display error message
			if [ "${proc_id_array[$count_proc_id]}" -ne "0" ]; then
				kill ${proc_id_array[$count_proc_id]} > /dev/null 2>&1
				echo "$DATE: ${proc_name_array[$count_proc_id]} \(PID: ${proc_id_array[$count_proc_id]}\) stopped." >> $logfile
				proc_id_array[$count_proc_id]=0 #identify driver as inactive
			   echo "Channel ${proc_name_array[$count_proc_id]} stopped."
			else
				#Tell user that Driver is not running, no need to shutdown
				echo "Error: ${proc_name_array[$count_proc_id]} not running."
			fi
			folder=${act_inst_array[$count_proc_id]}
			DATE=$(date +%m%d%y-%k:%M)
			proc_id_array[$count_proc_id]="0"		
			count_proc_id=`expr $count_proc_id + 1`
		done
	
		if [ -e "./Data/.locked" ]; then
			rm -f ./Data/.locked
		fi
		echo "datalogger stopped"
		datalogger_on=0
		#sed -e 's/\('start_logger'=\).*/\1\"'"0"'\"/' <./Config/config>./Config/config.tmp
		#cp ./Config/config.tmp  ./Config/config
		sleep 5
	else
		echo "Datalogger already stopped."
		sleep 1
	fi
}

####################################################################################################
#
#START DATALOGGER FUNCTION
#
####################################################################################################
d_startup () {
	if [ "$1" = "log" ]; then
		DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
		echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
		echo "in start" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
	fi
	clear
	#temp fix, start logger modified to run through entire function to accomodate new functions
	if [ "$datalogger_on" -eq 0 ] || [ "$datalogger_on" -eq 1 ]; then
		echo "starting Datalogger"
		count_proc_id=1
		count_act_inst=1
		max_proc_id=0
		while [ "$count_act_inst" -lt "$max_act_inst" ]; do
			folder=${act_inst_array[$count_act_inst]}
			#echo "current folder : $folder" ##DEBUG##
			collocated_inst=$(ls ./resources/$folder/.usr*)
			#echo "current col_inst : $collocated_inst" ##DEBUG##
			counter=1
			for i in $collocated_inst; do
				temp=$(echo "${i#./*/*/.usr}")
				#echo "temp : $temp" ##DEBUG##
				coll_array[$counter]=$temp
				#echo "${coll_array[$counter]}" ##DEBUG##
				counter=`expr $counter + 1`
			done
			max_coll="$counter"
			counter=1
			while [ "$counter" -lt "$max_coll" ]; do
				#echo "in while counter : $counter" ##DEBUG##
				#echo "coll_array : ${coll_array[$counter]}" ##DEBUG##
				init_str=`cat ./resources/"$folder"/".usr${coll_array[$counter]}"`
				save_name_flag=0
				upper_flag=0
				lower_flag=0
				for i in $init_str; do
					if [ "$save_name_flag" -eq 1 ]; then #save token as driver name in name arrary
						proc_name_array[$count_proc_id]="$i"
						save_name_flag=0
					fi
					if [ "$i" = "-r" ]; then #if token matches -r, set flag so next token is read as driver name
						save_name_flag=1
					fi
					if [ "$i" = "-U" ]; then #set upper flow flag so next token is saved as upper flow bound
						upper_flag=1
					fi
					if [ "$i" = "-L" ]; then #set lower flow flag so next token is saved as lower flow bound
						lower_flag=1
					fi
				done
		
				flag=0
				command="./resources/$folder/testd $init_str-I ${coll_array[$counter]} -s $saroad"
				#echo "$command"  ###DEBUG
				if [ "$upper_flag" -eq 1 ]; then
					echo -n ""  ###placeholder
					#command="$command -U "  add variable for upper
				fi
				if [ "$lower_flag" -eq 1 ]; then
					echo -n ""  ###placeholder
					#command="$command -L " add variable for lower
				fi
				command="$command &"
				#echo "$command"  ###DEBUG
				#####NEW CHECK STATEMENT TO SEE IF INSTRUMENT IS CURRENTLY RUNNING#####
				if [ "${proc_id_array[$count_proc_id]}" -gt 0 ]; then
					echo "${proc_name_array[$count_proc_id]} already running"
				else
					eval $command > /dev/null
					proc_id_array[$count_proc_id]=$!
					echo "initializing ${proc_name_array[count_proc_id]}"
					echo "$DATE: ${proc_name_array[$count_proc_id]} \(PID: ${proc_id_array[$count_proc_id]}\) started." >> $logfile
				fi
				###########END NEW STATEMENT
			
				#echo "${proc_id_array[$count_proc_id]}"  #DEBUG
				count_proc_id=`expr $count_proc_id + 1`
				max_proc_id="$count_proc_id"
				counter=`expr $counter + 1`
			done
			count_act_inst=`expr $count_act_inst + 1`
		done

		##Start Reporter and save process id
	
		if [ "${proc_id_array[$count_proc_id]}" -gt 0 ]; then
			echo "reporter already running"
		else
			./sys_resources/reporter.sh & > /dev/null
			proc_id_array[$count_proc_id]=$!
			#echo "${proc_id_array[$count_proc_id]}" ##DEBUG
			proc_name_array[$count_proc_id]="Reporter"
			echo "Starting Reporter"
			echo "$DATE: ${proc_name_array[$count_proc_id]} \(PID: ${proc_id_array[$count_proc_id]}\) started." >> $logfile
		fi
		count_proc_id=`expr $count_proc_id + 1`
		#echo "count_proc_id: $count_proc_id" ##DEBUG
		##Start Ingest Manager and save process id
		#echo "array_content: ${proc_id_array[count_proc_id]}" ##DEBUG	
#		if [ ${proc_id_array[$count_proc_id]} -gt 0 ]; then
#			echo "ingestmanager already running"
#		else
#			./sys_resources/ingestmanager.sh & > /dev/null
#			proc_id_array[$count_proc_id]=$!
#			proc_name_array[$count_proc_id]="Ingest Manager"
#			echo "Starting Ingest Manager"
#		fi
#		count_proc_id=`expr $count_proc_id + 1`
		max_proc_id="$count_proc_id"
		datalogger_on=1
		sed -e 's/\('start_logger'=\).*/\1\"'"1"'\"/' <./Config/config>./Config/config.tmp
		cp ./Config/config.tmp  ./Config/config
		sleep 5
	else
		echo "Datalogger already running."
		sleep 1
	fi
}

####################################################################################################
#
#EDIT SITE INFORMATION FUNCTION
#
####################################################################################################
edit_site () {
	clear
	if [ "$1" = "log" ]; then
		DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
		echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
		echo "in edit site" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
	fi
	while [ "$flag_site_op" -lt 1 ]; do
		clear
		echo "$site_parameter_name currently set to ${!site_parameter}"
		if [ "$yn_flag" -eq 1 ]; then
			echo " Enter new $site_parameter_name value (y/n, press enter for no change)"
		else
			echo "Enter new $site_parameter_name (press enter for no change)"
		fi
		echo -n ":>"
		flag_site_op=0
		t_error_flag=0
		save_flag=0
		read u_in
		if [ "$u_in" = "" ]; then
			echo "Change $site_parameter_name to ${!site_parameter} (y/n)?"
			echo -n ":>"
			read y_or_no
			if [ "$y_or_no" = "y" ]; then
				echo "$site_parameter_name changed to ${!site_parameter}"
				flag_site_op=1
				sleep 1
			else
				:
			fi
		else
			if [ "$time_flag" = 1 ]; then
				echo $u_in | grep "[^0-9]" > /dev/null 2>&1
				if [ "$?" -eq "0" ]; then
					echo "Invalid Input"
					t_error_flag=1
					sleep 1
				elif [ "$u_in" -gt 23 ] || [ "$u_in" -lt 0 ]; then
					echo "Invalid Input"
					sleep 1
					t_error_flag=1
				fi
			fi
		
			if [ "$yn_flag" -eq 1 ]; then
				if [ "$u_in" != "y" ] && [ "$u_in" != "n" ]; then
					echo "Invalid Input, must be \"y\" or \"n\""  
					t_error_flag=1
					sleep 1
				else
					:
				fi
			fi

			if [ "$t_error_flag" -eq 0 ]; then
				echo "Change $site_parameter_name to $u_in (y/n)?"
				read y_or_no
				if [ "$y_or_no" = "y" ]; then
					eval $site_parameter='$u_in'
					echo "$site_parameter_name changed to ${!site_parameter}"
					save_flag=1
					sleep 1
				else
					:
				fi
			fi
		fi

		if [ "$save_flag" -eq 1 ]; then
			sed -e 's/\('"$site_parameter"'=\).*/\1\"'"$u_in"'\"/' <./Config/config>./Config/config.tmp
			cp ./Config/config.tmp  ./Config/config
			flag_site_op=1
			echo "Returning to Site Information Menu"
			sleep 1
			flag_site_op=1
			restart_flag=1
		fi
	done
}

####################################################################################################
#
# DISABLED FLAG MENU FUNCTION
#
####################################################################################################
disabled_menu () {
	dm_exit_flag=0
	while [ "$dm_exit_flag" -eq "0" ]; do
		clear
		current_status=$(cat ./resources/${folder_array[$usr_input]}/.disabled${usr_array[$usr_input]})
		echo "Change ${d_name_array[$usr_input]} status to:"
		echo -n "1. Enabled "
		if [ "$current_status" -eq "0" ]; then
			echo "(*)"
		else
			echo ""
		fi
		echo -n "2. Offline "
		if [ "$current_status" -eq "1" ]; then
			echo "(*)"
		else
			echo ""
		fi
		echo -n "3. Routine Maintenance "
		if [ "$current_status" -eq "2" ]; then
			echo "(*)"
		else
			echo ""
		fi
		echo -n "4. Instrument Repair "
		if [ "$current_status" -eq "3" ]; then
			echo "(*)"
		else
			echo ""
		fi
		echo -n "5. Manual Calibration "
		if [ "$current_status" -eq "4" ]; then
			echo "(*)"
		else
			echo ""
		fi
		echo -n "6. QA Audit "
		if [ "$current_status" -eq "5" ]; then
			echo "(*)"
		else
			echo ""
		fi
		echo -n "7. Zero Test "
		if [ "$current_status" -eq "6" ]; then
			echo "(*)"
		else
			echo ""
		fi
		echo "q. Return to Disable Instruments Menu"
		echo -n ":>"
		dm_non_int_flag=0
		read dm_usr_input
		#echo "$dm_usr_input" #DEBUG
		echo $dm_usr_input | grep "[^0-9]" > /dev/null 2>&1
		if [ "$?" -eq "0" ]; then
			if [ "$dm_usr_input" == "q" ] || [ "$dm_usr_input" == "Q" ]; then
				echo "Exiting Disable Instrument Menu"
				dm_exit_flag=1
				dm_activate_flag=0
				dm_non_int_flag=1
				sleep 1
			else
				echo "Invalid Input"
				dm_activate_flag=0
				dm_non_int_flag=1
				sleep 1
			fi
		fi
		if [ "$dm_non_int_flag" -eq 0 ]; then
			if [ "$dm_usr_input" = "" ]; then
				echo "Invalid Input"
				dm_activate_flag=0
				sleep 1
			elif [ "$dm_usr_input" -gt "7" ] || [ "$dm_usr_input" -lt 0 ]; then
				echo "Invalid Input"
				dm_activate_flag=0
				sleep 1
				else
				dm_activate_flag=1
			fi
			#WRITE TO THE DISABLED FILE
			if [ "$dm_activate_flag" -eq 1 ]; then
				dm_usr_input=`expr $dm_usr_input - 1`
				echo "$dm_usr_input" > ./resources/${folder_array[$usr_input]}/.disabled${usr_array[$usr_input]}
				echo -n "${d_name_array[$usr_input]} flagged "
				case "$dm_usr_input" in
					"0" )
						echo "Enabled"
					;;
					"1" )
						echo -e "Disabled"
					;;
					"2" )
						echo -e "Routine Maintenance"
					;;
					"3" )
						echo -e "Instrument Repair"
					;;
					"4" )
						echo -e "Manual Calibration"
					;;
					"5" )
						echo -e "QA Audit"
					;;
					"6" )
						echo -e "Zero Test"
					;;
				esac
				sleep 1
			fi
		fi
	done
}

####################################################################################################			
#
#MAIN PROGRAM CODE
#
####################################################################################################
DATE=$(date +%m%d%y-%k:%M)
#Datalogger Initiated Flag
datalogger_on=0
logfile="Data/CARBLogger.log"
echo "$DATE: CARBLogger Started." >> $logfile
#initialize general purpose counter variable 
counter=1

#
#seed calibration flag list (cal_flag_array[]) to disabled (0 is disabled, 1 is enabled)
#
cal_flag_array_idx=1 #array navigator variable
while [ "$cal_flag_array_idx" -lt "$max_act_inst" ]; do
	cal_flag_array[$cal_flag_array_idx]="0"  # array for marking programmed channels
	cal_flag_array_idx=`expr $cal_flag_array_idx + 1`
done

#populate process_id list of active channels with "A" to protect from inadvertant process kills
proc_id_array_idx=1 #array navigator variable
max_pid=`expr $max_act_inst + 2` #add 2 to adjust for reporter and ingest scripts
while [ "$proc_id_array_idx" -lt "$max_pid" ]; do
	proc_id_array[$proc_id_array_idx]="0"  # array for marking programmed channels
	#echo " starting value : ${proc_id_array[$proc_id_array_idx]}" ##DEBUG
	proc_id_array_idx=`expr $proc_id_array_idx + 1`
done

#calculate the elevation correction factor
alt_correct=$(awk  -v alt=$elevation '
BEGIN { long=1.001*2.71828^(-0.0000371*alt)
print long;
exit;
}')

#initialize user input
usr_input="0"
usr_input3="0"
main_exit=0
#loop while user input is not "q", the quit signal

if [ "$start_logger" -eq 1 ] && [ "$datalogger_on" -eq 0 ]; then
	d_startup
fi

while [ "$main_exit" != "1" ]; do
	if [ "$1" = "log" ]; then
	DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
		echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
		echo "in main menu loop" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
		ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
	fi
	#read config file
	while read line; do
		eval $line
	done < Config/config

	#read and store the list or drivers
	#list all folders in resources labelled *drv (shows available instruments)
	drv_folders=$(ls resources | grep drv)
	count_drv=1  #counter variable
	for i in $drv_folders; do
		drv_list[$count_drv]="$i"
		count_drv=`expr $count_drv + 1`
		max_count_drv="$count_drv"
	done

	#Create array of active/configured instruments from config file
	count_act_inst=1
	max_act_inst=0
	for i in $active_inst; do
		act_inst_array[$count_act_inst]="$i"
		count_act_inst=`expr $count_act_inst + 1`
		max_act_inst="$count_act_inst"
	done


	#Find Available Serial Ports and populate spt_array with values
	#MOVED THIS TO THE CONFIG FILE AND MODIFIED TO WORK WITH PERLE --MJV	
	#serial_ports=$(ls /dev/ttyPS[0-7] && ls /dev/ttyS*)
	spt_array_nav=1

	for i in $serial_ports; do
		spt_array[$spt_array_nav]="$i"
		spt_array_nav=`expr $spt_array_nav + 1`
	done
	spt_array_max="$spt_array_nav"

	#
	#seed calibration flag list (cal_flag_array[]) to disabled (0 is disabled, 1 is enabled)
	#
	cal_flag_array_idx=1 #array navigator variable
	while [ "$cal_flag_array_idx" -lt "$max_act_inst" ]; do
		cal_flag_array[$cal_flag_array_idx]="0"  # array for marking programmed channels
		cal_flag_array_idx=`expr $cal_flag_array_idx + 1`
	done

	clear
	#Menu Options list
	echo "WELCOME TO CARBLOG"
	echo ""
	
	if [ "$datalogger_on" -eq 1 ]; then
		echo "Datalogger On"
	else
		echo "Datalogger Off"
	fi
	echo ""
	echo "1.  Start/Stop Instruments/Datalogger"
	echo "2.  Add instrument"
	echo "3.  Edit instrument"
	echo "4.  Delete instrument"
	echo "5.  Enable/Disable Channels"
	echo "6.  Display Channels"
	echo "7.  Edit Station Details"
	echo "8.  Clear Station and Instrument Settings"
	echo "9.  Generate Raw Monthly Data Extract"
	echo "q.  Quit Datalogger"
	echo -n ":>"

	#Take User Input
	read usr_input
	
	case "$usr_input" in 

##############################################################################################
#
#					 Start/Stop Datalogger
#
##############################################################################################

	"1" ) #Start/Stop Datalogging 
		if [ "$1" = "log" ]; then
			DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
			echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
			echo "in stop datalogging" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
		fi
		shutdown_menu_exit=0
		while [ "$shutdown_menu_exit" -eq 0 ]; do
			clear
			echo "Start/Stop Datalogger Menu"
			#####create menu of active instruments#####
		
			name_array_counter=1 #counter for navigating proc_name_array
			menu_counter=1 #counter for creating menu numbers
			while [ "$name_array_counter" -lt "$max_act_inst" ]; do
				if [ "${proc_id_array[$name_array_counter]}" -eq 0 ]; then 		
		 			echo -e '\E[31m'"$menu_counter. ${proc_name_array[$name_array_counter]} (OFF)"'\E[30m'
   		 		else
	   		 		echo "$menu_counter. ${proc_name_array[$name_array_counter]}"
	   		 	fi
   		 		menu_counter=`expr $menu_counter + 1` #increment menu numbers
				name_array_counter=`expr $name_array_counter + 1` #increment array counter
			done 
			start_op="$menu_counter"
			echo "$start_op. Start Datalogger (All Instruments and Data Reporting)"			
			menu_counter=`expr $menu_counter + 1` #increment menu numbers			
			echo "$menu_counter. Stop Datalogger (All Instruments and Data Reporting)"
			echo "q. Exit Stop Datalogger Menu"
			echo -n ":>"
			read usr_input
			non_int_flag=0
			echo $usr_input | grep "[^0-9]" > /dev/null 2>&1
			if [ "$?" -eq "0" ]; then
				non_int_flag=1	##mark user input as a string
				#Exit Menu on Q or q
				if [ "$usr_input" == "q" ] || [ "$usr_input" == "Q" ]; then #flag as user selecting menu exit
					echo "Exiting Start/Stop Datalogger Menu"
					shutdown_menu_exit=1
					sleep 1
				else
					#Non-integer string input, non exit user input error test case
					echo "Invalid Input"
					input_error_flag=1 #flag invalid input
					sleep 1
				fi
			elif [ "$usr_input" -gt "$menu_counter" ]; then #test for number beyond menu range
				echo "Invalid Input, number out of range"
				sleep 1
			elif [ "$usr_input" -eq "$start_op" ]; then
				d_startup
			elif [ "$usr_input" -eq "$menu_counter" ]; then #user chose shutdown all, call d_shutdown function to stop datalogger
				d_shutdown
			else
				#Turn on/off single  instrument
				#pid_check=$(ps "${proc_id_array[$usr_input]}" | wc -l)
				#[ "$pid_check" -eq 1 ] ||
				#see if PID in array is 0 or a real process
				#Start process if array value is 0
				if [ "${proc_id_array[$usr_input]}" -eq 0 ]; then
					inst_folder="${act_inst_array[$usr_input]}"
					init_str=`cat ./resources/"$inst_folder"/".usr1"`
					inst_command="./resources/$inst_folder/testd $init_str-I 1 -s $saroad &"
					eval $inst_command > /dev/null					
					proc_id_array[$usr_input]=$!					
					echo "Starting ${proc_name_array[$usr_input]}"
					echo "$DATE: ${proc_name_array[$usr_input]} \(PID: ${proc_id_array[$usr_input]}\) started." >> $logfile
					sleep 1
				else
					#kill individual driver process
					kill ${proc_id_array[$usr_input]} > /dev/null 2>&1
					#Change array to 0 to indicate a non-running driver
					echo "$DATE: ${proc_name_array[$usr_input]} \(PID: ${proc_id_array[$usr_input]}\) stopped." >> $logfile
					proc_id_array[$usr_input]=0
					echo "${proc_name_array[$usr_input]} stopped"
					sleep 1
				fi
			fi	
		done				
		
		#call shutdown function
		#d_shutdown
	;;

##############################################################################################
#
#ADD INSTRUMENT
#
##############################################################################################
	"2" ) #Add Instrument
		if [ "$1" = "log" ]; then
			DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
			echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
			echo "in add instrument" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
		fi
		menu_flag=0 #
		edit_flag=0 #
		restart_d=0
		while [ "$menu_flag" -eq 0 ]; do
			clear
			counter=1 #array navigator
			array_count=1
			while [ "$counter" -lt "$max_act_inst" ]; do
				folder="${act_inst_array[$counter]}"
				usr_count=$(ls -B ./resources/$folder/.usr*)
				for i in $usr_count; do
					temp=$(echo "${i#./*/*/.usr}")
					folder_array[$array_count]="$folder"
					a_i_array[$array_count]="$counter"
					usr_array[$array_count]="$temp"
					init_str=`cat ./resources/"$folder"/.usr"$temp"`
					save_name_flag=0
					save_spt_flag=0
					for i in $init_str; do
						if [ "$save_name_flag" -eq 1 ]; then
							d_name_array[$array_count]="$i"
							save_name_flag=0
						fi
						if [ "$i" = "-r" ]; then
							save_name_flag=1
						fi
						if [ "$save_spt_flag" -eq 1 ]; then
							u_spt_array[$array_count]="$i"
							#echo "array_count = $array_count : sp = ${u_spt_array[$array_count]}" ##DEBUG##
							save_spt_flag=0
						fi
						if [ "$i" = "-d" ]; then
							save_spt_flag=1
						fi 
					done
					array_count=`expr $array_count + 1`
				done
				counter=`expr $counter + 1`
			done
			array_count_max="$array_count"
			exist_flag=0
			count_drv=1
			input_error_flag=0 #Flag to indicate user input error, 1 indicates error, 0 for valid input
			echo "Select Instrument to Add"
			while [ "$count_drv" -lt "$max_count_drv" ]; do
				echo ""$count_drv". "${drv_list[$count_drv]}""
				count_drv=`expr $count_drv + 1`
			done
			echo "q. Return To Main Menu"
			echo -n ":>"
			read usr_input
			non_int_flag=0
			echo $usr_input | grep "[^0-9]" > /dev/null 2>&1
			if [ "$?" -eq "0" ]; then
				non_int_flag=1	##mark user input as a string
				if [ "$usr_input" == "q" ] || [ "$usr_input" == "Q" ]; then #flag as user selecting menu exit
					echo "Exiting Instrument Addition Menu"
					menu_flag=1
					input_error_flag=1 
					sleep 1
				else
					#Non-integer string input, non exit user input error test case
					echo "Invalid Input"
					input_error_flag=1 #flag invalid input
					sleep 1
				fi
			fi
			##CHECK FOR INPUT ERRORS###
			instrument="$usr_input" #store user input in a variable
			error_message=1
			if [ "$non_int_flag" -eq 0 ]; then  ##check to see if user input is a string
				#Check to see if user selection is larger than list or zero
				if [ "$instrument" -ge "$max_count_drv" ] || [ "$instrument" -eq 0 ]; then
					echo "Invalid Input"
					sleep 1
					input_error_flag=1 #flag user input error
				fi
			fi
			config_id=0
		
			if [ "$input_error_flag" -eq 0 ]; then #valid user input/non-exit input, continue through menu structure
				inst_name="${drv_list[$instrument]}"
				#echo "$inst_name" ##DEBUG##
				#ADD INST TO ACTIVE INSTRUMENT ARRAY AND CONFIG
				#
				collocated_inst=$(ls ./resources/$inst_name/.usr* 2>/dev/null)
				#echo "$collocated_inst" ##DEBUG
				if [ -n "$collocated_inst" ]; then
					counter=1
					max_inst=0
					for i in $collocated_inst; do
						temp=$(echo "${i#./*/*/}")
						avail_array[$counter]=$temp
						temp_max=$(echo "${avail_array[$counter]#.usr}")
						if [ "$temp_max" -gt "$max_inst" ]; then
							max_inst="$temp_max"
						fi
						counter=`expr $counter + 1`
					done
					max_counter="$counter"
					restart_d=0
					if [ "$max_counter" -gt 0 ]; then
						fin_menu=0
						while [ "$fin_menu" -eq 0 ]; do
							clear
							while [ "$counter" -lt "$max_act_inst" ]; do
								folder="${act_inst_array[$counter]}"
								usr_count=$(ls ./resources/$folder/.usr*)
								for i in $usr_count; do
									temp=$(echo "${i#./*/*/.usr}")
									folder_array[$array_count]="$folder"
									a_i_array[$array_count]="$counter"
									usr_array[$array_count]="$temp"
									init_str=`cat ./resources/"$folder"/.usr"$temp"`
									save_name_flag=0
									save_spt_flag=0
									for i in $init_str; do
										if [ "$save_name_flag" -eq 1 ]; then
											d_name_array[$array_count]="$i"
											save_name_flag=0
										fi
										if [ "$i" = "-r" ]; then
											save_name_flag=1
										fi
										if [ "$save_spt_flag" -eq 1 ]; then
											u_spt_array[$array_count]="$i"
											save_spt_flag=0
										fi
										if [ "$i" = "-d" ]; then
											save_spt_flag=1
										fi 
									done
									array_count=`expr $array_count + 1`
								done
								counter=`expr $counter + 1`
							done
							array_count_max="$array_count"
							echo "$max_inst configuration(s) found for $inst_name.  Add another configuration?"
							echo -n ":>"
							read one_or_two
							if [ "$one_or_two" = "y" ] || [ "$one_or_two" = "Y" ]; then
								param=`cat ./resources/${drv_list[$usr_input]}/.default`
								#echo "Adding configuration "
								config_id=`expr $max_inst + 1`
								#echo "c_id | $config_id" ##DEBUG
								edit_instrument
								fin_menu=1
								restart_d=1
							elif [ "$one_or_two" = "n" ] || [ "$one_or_two" = "N" ]; then
								echo "leaving instrument addition menu"
								fin_menu=1
							else
								echo "invalid input"
								sleep 1
							fi
						done
					fi
				else
					param=`cat ./resources/${drv_list[$usr_input]}/.default`
					echo "Adding configuration "
					config_id=1
					edit_instrument
					fin_menu=1
					restart_d=1
				fi
			fi
		done
		################################
		####Shut down datalogger if on to initiate config changes####
		#echo "\"$datalogger_on\""  ## DBUG
		#echo "\"$restart_d\""##DEBUG
		if [ $datalogger_on -eq 1 ] && [ $restart_d -eq 1  ]; then
			d_shutdown
			sleep 10
			######Restart Datalogger to initiate configuration changes#######
			d_startup
		fi
	;;

#######################################################################################
#
#Edit Instrument
#
#######################################################################################

	"3" ) #Edit Instrument_count
		if [ "$1" = "log" ]; then
			DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
			echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
			echo "in edit instrument" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
		fi
		quit_flag=0 #flag to indicate user input to return to main menu
		restart_d=0 #flag to indicate changes that require datalogger restart
		while [ "$quit_flag" -eq 0 ]; do #continue in menu structure until user inputs "q" or "Q"
			clear
			echo "Select Channel to Edit"
			counter=1
			enable_option_count=1
			array_count=1
			while [ "$counter" -lt "$max_act_inst" ]; do
				folder="${act_inst_array[$counter]}"
				usr_count=$(ls -B ./resources/$folder/.usr*)
				for i in $usr_count; do
					temp=$(echo "${i#./*/*/.usr}")
					folder_array[$array_count]="$folder"
					a_i_array[$array_count]="$counter"
					usr_array[$array_count]="$temp"
					init_str=`cat ./resources/"$folder"/.usr"$temp"`
					save_name_flag=0
					save_spt_flag=0
					for i in $init_str; do
						if [ "$save_name_flag" -eq 1 ]; then
							d_name_array[$array_count]="$i"
							save_name_flag=0
						fi
						if [ "$i" = "-r" ]; then
							save_name_flag=1
						fi
						if [ "$save_spt_flag" -eq 1 ]; then
							u_spt_array[$array_count]="$i"
							save_spt_flag=0
						fi
						if [ "$i" = "-d" ]; then
							save_spt_flag=1
						fi 
					done
					array_count=`expr $array_count + 1`
				done
				counter=`expr $counter + 1`
			done
			array_count_max="$array_count"
			array_count="1"
			while [ "$array_count" -lt "$array_count_max" ]; do
				echo ""$array_count". "${d_name_array[$array_count]}""
				array_count=`expr $array_count + 1`
			done
			
			echo "q.  Return To Main Menu"
			echo -n ":>"
			non_int_flag=0
			read usr_input
			echo $usr_input | grep "[^0-9]" > /dev/null 2>&1
			if [ "$?" -eq "0" ]; then	
				if [ "$usr_input" == "q" ] || [ "$usr_input" == "Q" ]; then
					echo "Exiting Edit Instrument Menu"
					quit_flag=1 #indicates user chose to exit Add instrument menu
					error_flag=1
					non_int_flag=1
					sleep 1
				else
					echo "Invalid Input"
					error_flag=1
					non_int_flag=1
					sleep 1
				fi
			fi
			temp_count=1
			if [ "$non_int_flag" -eq 0 ]; then
				if [ "$usr_input" = "" ]; then
					echo "Invalid Input"
					error_flag=1
					sleep 1
				elif [ "$usr_input" -gt "$array_count_max" ] || [ "$usr_input" -lt 0 ]; then
					echo "Invalid Input"
					error_flag=1
					sleep 1
				else
					error_flag=0
				fi

				if [ "$error_flag" -eq 0 ]; then
					#param stores the sjinn command string for edit instrument function
					param=`cat ./resources/${folder_array[$usr_input]}/.usr${usr_array[$usr_input]}`
					config_id="${usr_array[$usr_input]}"
					edit_flag=1
					inst_name="${folder_array[$usr_input]}"
					edit_instrument
					restart_d=1
				fi
			fi
		done
		####Shut down datalogger if on####
		if [ "$datalogger_on" -eq 1 ] && [ "$restart_d" -eq 1 ]; then
			d_shutdown
			sleep 10
			d_startup
		fi
	;;

###############################################################################################
#
#Delete Instrument Function
#
###############################################################################################

	"4" ) #Delete Instrument 
		if [ "$1" = "log" ]; then
			DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
			echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
			echo "in delete instrument" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
		fi
		quit_flag=0 #flag for exiting menu loop, set to 1 to exit
		while [ "$quit_flag" -eq 0 ]; do
			clear
			echo "Select Channel to Delete"
			counter=1
			enable_option_count=1
			array_count=1
			while [ "$counter" -lt "$max_act_inst" ]; do
				folder="${act_inst_array[$counter]}"
				usr_count=$(ls -B ./resources/$folder/.usr*)
				for i in $usr_count; do
					temp=$(echo "${i#./*/*/.usr}")
					folder_array[$array_count]="$folder"
					a_i_array[$array_count]="$counter"
					usr_array[$array_count]="$temp"
					init_str=`cat ./resources/"$folder"/.usr"$temp"`
					save_name_flag=0
					save_spt_flag=0
					for i in $init_str; do
						if [ "$save_name_flag" -eq 1 ]; then
							d_name_array[$array_count]="$i"
							save_name_flag=0
						fi
						if [ "$i" = "-r" ]; then
							save_name_flag=1
						fi
						if [ "$save_spt_flag" -eq 1 ]; then
							u_spt_array[$array_count]="$i"
							save_spt_flag=0
						fi
						if [ "$i" = "-d" ]; then
							save_spt_flag=1
						fi 
					done
					array_count=`expr $array_count + 1`
				done
				counter=`expr $counter + 1`
			done
			array_count_max="$array_count"
			array_count="1"
			while [ "$array_count" -lt "$array_count_max" ]; do
				echo ""$array_count". "${d_name_array[$array_count]}""
				array_count=`expr $array_count + 1`
			done
			echo "q.  Return To Main Menu"
			echo -n ":>"
			non_int_flag=0
			read usr_input
			echo $usr_input | grep "[^0-9]" > /dev/null 2>&1
			if [ "$?" -eq "0" ]; then	
				if [ "$usr_input" == "q" ] || [ "$usr_input" == "Q" ]; then
					echo "Exiting Delete Instrument Menu"
					quit_flag=1
					error_flag=1
					non_int_flag=1
					sleep 1
				else
					echo "Invalid Input"
					error_flag=1
					non_int_flag=1
					sleep 1
				fi
			fi
			temp_count=1
			if [ "$non_int_flag" -eq 0 ]; then
				if [ "$usr_input" = "" ]; then
					echo "Invalid Input"
					error_flag=1
					sleep 1
				elif [ "$usr_input" -ge "$array_count_max" ] || [ "$usr_input" -lt 0 ]; then
					echo "Invalid Input"
					error_flag=1
					sleep 1
				else
					error_flag=0
				fi

				if [ "$error_flag" -eq 0 ]; then
					echo "Are you sure you want to delete "${d_name_array[$usr_input]}"?"
					echo -n ":>"
					read y_n_input
					echo $y_n_input | grep "[^0-9]" > /dev/null 2>&1
					if [ "$?" -eq "0" ]; then	
						if [ "$y_n_input" == "n" ] || [ "$y_n_input" == "N" ]; then
							echo "aborting delete"
							quit_flag=0
							sleep 1
						fi
						if [ "$y_n_input" == "y" ] || [ "$y_n_input" == "Y" ]; then
							echo "deleting "${d_name_array[$usr_input]}""
							usr_count=$(ls ./resources/${folder_array[$usr_input]}/.usr*)
							max_inst=0
							for i in $usr_count; do
								max_inst=`expr $max_inst + 1`
							done
							if [ "$max_inst" -eq 1 ]; then
								rm -f ./resources/${folder_array[$usr_input]}/.usr${usr_array[$usr_input]}
								rm -f ./resources/${folder_array[$usr_input]}/.disabled${usr_array[$usr_input]}
								del_count="${a_i_array[$usr_input]}"
								#echo "$del_count | del count" ## DEBUG
								max_act_inst_minus_1=`expr $max_act_inst - 1`
								while [ "$del_count" -lt "$max_act_inst" ]; do
									if [ "$del_count" -lt "$max_act_inst_minus_1" ]; then
										#echo "in then" ##DEBUG
										del_count_1=`expr $del_count + 1`
										act_inst_array[$del_count]="${act_inst_array[$del_count_1]}"
										del_count=`expr $del_count + 1`
									else
										#echo " in else : $del_count"  ##DEBUG
										del_count_minus_1=`expr $del_count - 1`
										act_inst_array[$del_count]=""
										del_count=`expr $del_count + 1`
									fi
								done
								max_act_inst=`expr $max_act_inst - 1`
								act_inst_count=1
								while [ "$act_inst_count" -le "$max_act_inst" ]; do
									if [ "$act_inst_count" -eq 1 ]; then
										act_inst_temp="${act_inst_array[$act_inst_count]}"
										#echo "first|$act_inst_temp|" ##DEBUG
										act_inst_count=`expr $act_inst_count + 1`
									else
										#echo "pre_append|$act_inst_temp|" ##DEBUG
										act_inst_temp="$act_inst_temp ${act_inst_array[$act_inst_count]}"
										#echo "post_append|$act_inst_temp|" ##DEBUG
										act_inst_count=`expr $act_inst_count + 1`
									fi
								done
								active_inst="$act_inst_temp"
								#echo "ACTIVE INST : $active_inst" ##DEBUG
								sed --e 's/\(active_inst=\).*/\1\"'"$active_inst"'\"/' <./Config/config>./Config/config.tmp
								cp ./Config/config.tmp ./Config/config
								restart_d=1
							else
								rm -f ./resources/${folder_array[$usr_input]}/.usr${usr_array[$usr_input]}
								rm -f ./resources/${folder_array[$usr_input]}/.disabled${usr_array[$usr_input]}
								counter="${usr_array[$usr_input]}"
								max_inst=`expr $max_inst - 1`
								while [ "$counter" -le "$max_inst" ]; do
									counter_1=`expr $counter + 1`
									mv ./resources/${folder_array[$usr_input]}/.usr$counter_1 ./resources/${folder_array[$usr_input]}/.usr$counter
									mv ./resources/${folder_array[$usr_input]}/.disabled$counter_1 ./resources/${folder_array[$usr_input]}/.disabled$counter
									counter=`expr $counter + 1`
									restart_d=1
								done
							fi
						fi
					else
						echo "Invalid Input"
						error_flag=1
						non_int_flag=1
						sleep 1
					fi
				fi
			fi
		done
		
		####Shut down datalogger if on####
		if [ "$datalogger_on" -eq 1 ] && [ "$restart_d" -eq 1 ]; then
			d_shutdown
			sleep 10
			d_startup
		fi
	;;
	
######################################################################################################	
#
#						ENABLE CHANNEL - .disabled stores a 0
#
######################################################################################################
	"5" ) #Enable Channel (changed to List Instruments temp)
		if [ "$1" = "log" ]; then
			DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
			echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
			echo "in enable" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
		fi
		quit_flag=0 #loop flag to refresh menu unless user chooses to exit
		while [ "$quit_flag" -eq 0 ]; do
			clear
			activate_flag=0 #flag to carry out enable channel function
			error_flag=0
			echo "Enable/Disable Channels"
			counter=1
			enable_option_count=1
			array_count=1
			while [ "$counter" -lt "$max_act_inst" ]; do
				folder="${act_inst_array[$counter]}"
				usr_count=$(ls -B ./resources/$folder/.usr*)
				for i in $usr_count; do
					temp=$(echo "${i#./*/*/.usr}")
					folder_array[$array_count]="$folder"
					usr_array[$array_count]="$temp"
					init_str=`cat ./resources/"$folder"/.usr"$temp"`
					save_name_flag=0
					for i in $init_str; do
						if [ "$save_name_flag" -eq 1 ]; then
							d_name_array[$array_count]="$i"
							save_name_flag=0
						fi
						if [ "$i" = "-r" ]; then
							save_name_flag=1
						fi
					done
					array_count=`expr $array_count + 1`
				done
				counter=`expr $counter + 1`
			done
			array_count_max="$array_count"
			array_count=1
			valid_count=0
		
			#Display Menu
			while [ "$array_count" -lt "$array_count_max" ]; do
				if [ -e ./resources/${folder_array[$array_count]}/.disabled${usr_array[$array_count]} ]; then
					channel_status=$(cat ./resources/${folder_array[$array_count]}/.disabled${usr_array[$array_count]})
				else
					echo "0" > ./resources/${folder_array[$array_count]}/.disabled${usr_array[$array_count]}
					channel_status=$(cat ./resources/${folder_array[$array_count]}/.disabled${usr_array[$array_count]})
				fi
				status_array[$array_count]="$channel_status"
				if [ "$channel_status" -eq 0 ]; then
					echo -n ""$array_count". "${d_name_array[$array_count]}" "
				else
					echo -e -n '\E[31m'""$array_count". "${d_name_array[$array_count]}" "'\E[30m'
				fi 
				case "$channel_status" in
					"0" )
						echo "(Enabled)"
					;;
					"1" )
						echo -e '\E[31m'"(Offline)"'\E[30m'
					;;
					"2" )
						echo -e '\E[31m'"(Routine Maintenance)"'\E[30m'
					;;
					"3" )
						echo -e '\E[31m'"(Instrument Repair)"'\E[30m'
					;;
					"4" )
						echo -e '\E[31m'"(Manual Calibration)"'\E[30m'
					;;
					"5" )
						echo -e '\E[31m'"(QA Audit)"'\E[30m'
					;;
					"6" )
						echo -e '\E[31m'"(Zero Test)"'\E[30m'
					;;
				esac
				array_count=`expr $array_count + 1`
			done
		
			echo "q.  Return To Main Menu"
			echo -n ":>"
			non_int_flag=0
			read usr_input
			echo $usr_input | grep "[^0-9]" > /dev/null 2>&1
			if [ "$?" -eq "0" ]; then
				if [ "$usr_input" == "q" ] || [ "$usr_input" == "Q" ]; then
					echo "Exiting Enable Instrument Menu"
					quit_flag=1
					activate_flag=0
					non_int_flag=1
					sleep 1
				else
					echo "Invalid Input"
					activate_flag=0
					non_int_flag=1
					sleep 1
				fi
			fi
			temp_count=1
			if [ "$non_int_flag" -eq 0 ]; then
				if [ "$usr_input" = "" ]; then
					echo "Invalid Input"
					activate_flag=0
					sleep 1
				elif [ "$usr_input" -ge "$array_count" ] || [ "$usr_input" -lt 0 ]; then
					echo "Invalid Input"
					activate_flag=0
					sleep 1
				else
					activate_flag=1
				fi
				if [ "$activate_flag" -eq 1 ]; then
					disabled_menu
					sleep 1
				fi
			fi
		done
	;;

###################################################################################
#
#							DISPLAY CHANNEL
#
###################################################################################
	"6" ) #Display Channel Status
		
		clear
		usr_input=""
		counter=1
		n_and_t_count=1  ##Counter for name and token arrays
		array_count=1
		while [ "$counter" -lt "$max_act_inst" ]; do
			folder="${act_inst_array[$counter]}"
			if [ -e ./resources/$folder/.display ]; then
				usr_count=$(ls -B ./resources/$folder/.usr*)
				for i in $usr_count; do
					temp=$(echo "${i#./*/*/.usr}")
					display_raw=$(cat ./resources/$folder/.display)
					for i in $display_raw; do
						token_array[$array_count]=$i
						folder_array[$array_count]="$folder"
						usr_array[$array_count]="$temp"
						init_str=`cat ./resources/"$folder"/.usr"$temp"`
						save_name_flag=0
						for i in $init_str; do
							if [ "$save_name_flag" -eq 1 ]; then
								d_name_array[$array_count]="$i"
								save_name_flag=0
							fi
							if [ "$i" = "-r" ]; then
								save_name_flag=1
							fi
						done
						#.hourly file contains number of minutes before data is considered old.
						if [ -e ./resources/$folder/.hourly ]; then
							hourly_array[$array_count]=`cat ./resources/"$folder"/.hourly`
						else
							#default is 1 minute difference
							hourly_array[$array_count]=1
						fi
						array_count=`expr $array_count + 1`
					done
				done
			fi
			counter=`expr $counter + 1`
		done
		array_count_max="$array_count"
		while [ "$usr_input" = "" ]; do
			if [ "$1" = "log" ]; then
				DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
				echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
				echo "in display loop" >> $logfile   ##DEBUGLOG##
				ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
				ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
			fi
			#echo "third while"  ##############debug
			clear
			count_inst=1
			counter=1
			DATE2=$(date +20%y-%d-%m)
			filename="$saroad-$DATE2"
			if [ -e ./Data/$filename ]; then
				while [ "$counter" -lt "$array_count_max" ]; do
					not_found_flag=0
					disabled_flag=0
					
					#echo "fourth while"  ##############debug
					#echo "print counter : $counter" ###debug
					DATE2=$(date +20%y-%d-%m)
					PREV_DATE=$(date --date='yesterday' +20%y-%d-%m)
					filename="$saroad-$DATE2"
					prev_filename="$saroad-$PREV_DATE"
					#MJV last_val_raw=`cat ./Data/$filename | grep "^${d_name_array[$counter]}::" | grep "${token_array[$counter]}" | tail -n 1`
					last_val_raw=`cat ./Data/$filename | grep "${token_array[$counter]}" | tail -n 1`
					#echo "last val raw | $last_val_raw" ##DEBUG
					comp_date=$(date +%m-%d-%Y)
					current_time=$(date +%s) #time in seconds since 1970
					current_time=`expr $current_time / 60` #time in min since 1970
					file_timestamp=$(echo "$last_val_raw" | sed 's/.*_\([0-9][0-9]:[0-9][0-9]\).*/\1/')
					file_date=$(echo "$last_val_raw" | sed 's/.*\([0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]\).*/\1/')
					#echo "current_time | $current_time" ##DEBUG
					#file_day=${file_date:3:2}
					file_date_string="${file_date:6:4}-${file_date:0:2}-${file_date:3:2} $file_timestamp"
					file_time=$(date --date="$file_date_string" +%s)
					file_time=`expr $file_time / 60` #file time in min since 1970
					#echo "file time | $file_time" ##DEBUG
					time_diff=`expr $current_time - $file_time` #difference between system time and file time
					#echo "time_diff | $time_diff" ##DEBUG
					conc_value=$(echo "$last_val_raw" | sed 's/.*\('${token_array[$counter]}'\)\([-0-9]*\?.[0-9]*\).*/\2/')
					#echo "con_value raw | $conc_value" ##DEBUG
					#echo "$counter | $last_val_raw | $conc_value | ${d_name_array[$counter]}"   ###debug
					enabled_status=$(cat ./resources/${folder_array[$counter]}/.disabled${usr_array[$counter]})
					#echo "enabled_status | $enabled_status" ##DEBUG
					last_val_raw_status=$(echo "$last_val_raw" | grep "\-\-[A-Z][A-Z]*" | sed 's:.*\(\-\-[A-Z][A-Z]*\).*:\1:' | sed 's:\-\-::')
					#echo "last_val_status | $last_val_raw_status" ##DEBUG
					time_comparison_value=${hourly_array[$counter]}
					#echo "time_comparison_value | $time_comparison_value" ##DEBUG
					if [ "$last_val_raw" = "" ]; then
						echo -e '\E[31m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Instrument Not Found"'\E[30m'
					elif [ -n "$last_val_raw_status" ]; then
						case "$last_val_raw_status" in
							"OFFLINE" | "DISABLED" )
								echo -e '\E[31m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Offline"'\E[30m'
								;;
									
							"MAINTENANCE" )
								echo -e '\E[33m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Routine Maintenance"'\E[30m'
								;;
								
							"REPAIR" )
								echo -e '\E[32m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Instrument Repair"'\E[30m'
								;;
							
							"CALIBRATION" )
								echo -e '\E[34m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Manual Calibration"'\E[30m'
								;;
								
							"AUDIT" )
								echo -e '\E[35m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: QA Audit"'\E[30m'
								;;
						
							"ZERO" )
								echo -e '\E[36m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Zero Test"'\E[30m'
								;;
						esac
					elif [ "$enabled_status" -ne 0 ]; then
						case "$enabled_status" in
							"1" )
								echo -e '\E[31m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Offline"'\E[30m'
								;;
								
							"2" )
								echo -e '\E[33m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Routine Maintenance"'\E[30m'
								;;
							
							"3" )
								echo -e '\E[32m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Instrument Repair"'\E[30m'
								;;
								
							"4" )
								echo -e '\E[34m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Manual Calibration"'\E[30m'
								;;
								
							"5" )
								echo -e '\E[35m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: QA Audit"'\E[30m'
								;;
								
							"6" )
								echo -e '\E[36m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Channel Mode: Zero Test"'\E[30m'
								;;	
						esac
					elif [ "$file_date" != "$comp_date" ]; then #see if file datestamp does not match current day
					#PRINT DATA IN RED WITH WARNING
						echo -e '\E[31m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Data Date=$file_date"'\E[30m'
					else [ "$file_date" = "$comp_date" ] #see if file datestamp matches current day
						if [ "$time_diff" -le "$time_comparison_value" ]; then
							echo "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value" #Print in black, no warnings
						else
							echo -e '\E[31m' "${d_name_array[$counter]} : ${token_array[$counter]} $conc_value **WARNING:Data is $time_diff minutes old"'\E[30m'
						fi
					fi
					counter=`expr $counter + 1`
				done
			else
				echo "No datafile found for $DATE2"
			fi
			read -t 10 -s -n1 -p "Hit \"q\" or \"x\" To Return To Main Menu" usr_input
		done
	;;
####################################################################################################
#
#					 Edit System Details
#
####################################################################################################
	"7" ) #Edit system operator contact information
		r_to_main=0
		restart_flag=0
		if [ "$1" = "log" ]; then
			DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
			echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
			echo "in Edit system " >> $logfile   ##DEBUGLOG##
			ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
		fi
		while [ "$r_to_main" -lt 1 ]; do
			clear
			flag_site_op=0
			time_flag=0
			yn_flag=0
			echo "Edit Site Information"
			echo "1.  Site Operator E-mail ($siteop)"
			echo "2.  Site Secondary E-mail ($sitescnd)"
			echo "3.  Site Supervisor E-mail ($sitesup)"
			echo "4.  AQS Number ($saroad)"
			echo "5.  Site Elevation ($elevation)"
			echo "6.  Site Name ($sitnam)"
			echo "7.  1st Error Reporting Hour ($hour1)"
			echo "8.  2nd Error Reporting Hour ($hour2)"
			echo "9. E-mail Site Secondary ($scnd_email)"
			echo "q. Return To Main Menu"
			echo -n ":>"
			read usr_input

			case "$usr_input" in

				"1" )
					clear
					site_parameter_name="Site Operator E-mail"
					site_parameter="siteop"
					edit_site
				;;

				"2" )
					clear
					site_parameter_name="Site Second E-mail"
					site_parameter="sitescnd"
					edit_site
				;;

				"3" )
					clear
					site_parameter_name="Site Supervisor E-mail"
					site_parameter="sitesup"
					edit_site
				;;

				"4" )
					clear
					site_parameter_name="Site AIRS Number"
					site_parameter="saroad"
					edit_site
				;;
				
				"5" )
					clear
					site_parameter_name="Site Elevation"
					site_parameter="elevation"
					edit_site
				;;
				"6" )
					clear
					site_parameter_name="Site Name"
					site_parameter="sitnam"
					edit_site
				;;
				"7" )
					clear
					site_parameter_name="1st Error Reporting Hour (00-23)"
					site_parameter="hour1"
					time_flag=1
					edit_site
				;;
				"8" )
					clear
					site_parameter_name="2nd Error Reporting Hour (00-23)"
					site_parameter="hour2"
					time_flag=1
					edit_site
				;;
				"9" )
					clear
					site_parameter_name="E-mail status to Site Secondary"
					site_parameter="scnd_email"
					yn_flag=1
					edit_site
				;;
				"q" )
					r_to_main=1
					echo "Returning To Main Menu"
					sleep 1
					
					##stop/restart datalogger if any settings changed
					if [ "$restart_flag" -eq 1 ]; then
						d_shutdown
						d_startup
					fi
				;;
				"*" )
					echo "Invalid Input"
					sleep 1
				;;
			esac
		done
	;;
########################################################################################################
#
#					 CLEAR ALL SETTINGS
#
########################################################################################################
	"8" )
		clear
		menu_flag=0
		while [ "$menu_flag" -eq 0 ]; do
			clear
			echo "Clear all station and instrument settings? (y/n)"
			echo -n ":>"
			read usr_input
			if [ "$usr_input" = "n" ] ; then
				echo "Aborting Reset"
				sleep 1
				menu_flag=1
			elif [ "$usr_input" = "y" ]; then
				echo "ARE YOU SURE?"
				echo -n ":>"
				read usr_input2
				if [ "$usr_input2" = "n" ] ; then
					echo "Aborting Station Settings Reset"
					sleep 1
				elif [ "$usr_input" = "y" ]; then		
					##Set all config file parameters to null
					echo "Clearing Station Settings"
					sed -e 's/\('sitnam'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('siteop'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('sitescnd'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('sitesup'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('saroad'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('elevation'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('hour1'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('hour2'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('scnd_email'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('chn_last'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('active_chn'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('active_inst'=\).*/\1\"'""'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					sed -e 's/\('start_logger'=\).*/\1\"'"1"'\"/' <./Config/config>./Config/config.tmp
					cp ./Config/config.tmp  ./Config/config
					##delete all .usr* files
					echo "Clearing Instrument Settings"
					count_drv=1
					while [ "$count_drv" -lt "$max_count_drv" ]; do
						rm ./resources/${drv_list[$count_drv]}/.usr* 2>/dev/null
						rm ./resources/${drv_list[$count_drv]}/.disabled* 2>/dev/null
						count_drv=`expr $count_drv + 1`
					done
				
					echo "All Station and Instrument Settings Cleared"
					menu_flag=1
					sleep 1
					max_act_inst=0
					#stop/restart datalogger to refresh settings
					d_shutdown
					d_startup
				else				
					echo "Invalid Input"
					sleep 1
				fi				
			else
				echo "Invalid Input"
				sleep 1 
			fi
		done
	;;
########################################################################################################
#
#	RUN SPECIAL SCRIPTS
#
########################################################################################################
	"9" ) 
		r_to_main=0
		report_name=""
		report_month=""
		report_year=""
		report_email=""
		report_script=""
		
		while [ "$r_to_main" -eq 0 ]; do
			clear
			echo "Configure Monthly Instrument Report"
			echo "1. Instrument ($report_name)"
			echo "2. Month	 ($report_month)"
			echo "3. Year	  ($report_year)"
			echo "4. E-mail	($report_email)"
			echo "5. Data Script($report_script)"
			echo "6. Generate Report"
			echo "q. Return to Main Menu"
			echo -n ":>"
			read usr_input
			
			case "$usr_input" in
				"1" )
					clear
					quit_flag=0 #flag to indicate user input to return to main menu
					while [ "$quit_flag" -eq 0 ]; do #continue in menu structure until user inputs "q" or "
						clear
						echo "Select Channel for Monthly Report"
						counter=1
						enable_option_count=1
						array_count=1
						while [ "$counter" -lt "$max_act_inst" ]; do
							folder="${act_inst_array[$counter]}"
							usr_count=$(ls -B ./resources/$folder/.usr*)
							for i in $usr_count; do
								temp=$(echo "${i#./*/*/.usr}")
								folder_array[$array_count]="$folder"
								a_i_array[$array_count]="$counter"
								usr_array[$array_count]="$temp"
								init_str=`cat ./resources/"$folder"/.usr"$temp"`
								save_name_flag=0
								#save_spt_flag=0
								for i in $init_str; do
									if [ "$save_name_flag" -eq 1 ]; then
										d_name_array[$array_count]="$i"
										save_name_flag=0
									fi
									if [ "$i" = "-r" ]; then
										save_name_flag=1
									fi
									#if [ "$save_spt_flag" -eq 1 ]
									#then
									#	u_spt_array[$array_count]="$i"
									#	save_spt_flag=0
									#fi
									#if [ "$i" = "-d" ]
									#then
									#	save_spt_flag=1
									#fi 
								done
								array_count=`expr $array_count + 1`
							done	
							counter=`expr $counter + 1`
						done
						array_count_max="$array_count"
						array_count="1"
						while [ "$array_count" -lt "$array_count_max" ]; do
							if [ "$report_name" = "${d_name_array[$array_count]}" ]; then
								echo ""$array_count". * "${d_name_array[$array_count]}" *" 
								array_count=`expr $array_count + 1`
								quit_flag=1
							else
								echo ""$array_count". "${d_name_array[$array_count]}""
								array_count=`expr $array_count + 1`
								quit_flag=1
							fi
						done
			
						echo "q.  Return To Report Menu"
						echo -n ":>"
						non_int_flag=0
						read name_input
						echo $name_input | grep "[^0-9]" > /dev/null 2>&1
						if [ "$?" -eq "0" ]; then	
							if [ "$name_input" == "q" ] || [ "$name_input" == "Q" ]; then
								echo "Exiting Select Channel Menu"
								quit_flag=1 #indicates user chose to exit Add instrument menu
								error_flag=1
								non_int_flag=1
								sleep 1
							else
								echo "Invalid Input"
								error_flag=1
								non_int_flag=1
								sleep 1
							fi
						fi
						temp_count=1
						if [ "$non_int_flag" -eq 0 ]; then
							if [ "$name_input" = "" ]; then
								echo "Invalid Input"
								error_flag=1
								sleep 1
							elif [ "$name_input" -gt "$array_count_max" ] || ["$name_input" -lt 0 ]; then
								echo "Invalid Input"
								error_flag=1
								sleep 1
							else
								error_flag=0
							fi
							if [ "$error_flag" -eq 0 ]; then
								report_name="${d_name_array[$name_input]}"
							fi
						fi
					done
				;;
		
				"2" )
					clear
					echo -n "Enter the month (two digit format) to be processed or "q" to return to menu :>"			
					read month_input
					echo $month_input | grep "[^0-9]" > /dev/null 2>&1
					if [ "$?" -eq "0" ]; then	
						if [ "$month_input" == "q" ] || [ "$month_input" == "Q" ]; then
							echo "Exiting Edit Instrument Menu"
							quit_flag=1 #indicates user chose to exit Add instrument menu
							error_flag=1
							non_int_flag=1
							sleep 1
						else
							echo "Invalid Input"
							error_flag=1
							non_int_flag=1
							sleep 1
						fi
					else
						report_month="$month_input"	
					fi
				;;
			
				"3" )
					clear
					echo -n "Enter the year (four digit format) to be processed or q to return to report menu :>"
					read year_input
					echo $year_input | grep "[^0-9]" > /dev/null 2>&1
					if [ "$?" -eq "0" ]; then	
						if [ "$year_input" == "q" ] || [ "$year_input" == "Q" ]; then
							echo "Exiting Edit Instrument Menu"
							quit_flag=1 #indicates user chose to exit Add instrument menu
							error_flag=1
							non_int_flag=1
							sleep 1
						else
							echo "Invalid Input"
							error_flag=1
							non_int_flag=1
							sleep 1
						fi
					else
						report_year="$year_input"	
				
					fi
				;;
		
				"4" )
					clear
					echo -n "Enter the e-mail address for report delivery or q to return to report menu :>"
					read email_input
					if [ "$year_input" == "q" ] || [ "$year_input" == "Q" ]; then
						echo "Exiting Edit Instrument Menu" 
					else
						report_email="$email_input"
					fi
				;;
				
				"5" )
					clear
					data_script_list=`ls $home_folder/sys_resources/scripts`
					data_script_array_pointer=1
					data_script_array_max=1
					menu_exit=0
					for i in $data_script_list; do
						data_script_array[$data_script_array_pointer]="$i"
						data_script_array_pointer=`expr $data_script_array_pointer + 1`
						data_script_array_max=`expr $data_script_array_max + 1`
					done
					
					while [ "$menu_exit" -eq 0 ]; do
						clear
						data_script_array_pointer=1
						echo "report script set to :$report_script"
						while [ "$data_script_array_pointer" -lt "$data_script_array_max" ]; do
							echo "$data_script_array_pointer. ${data_script_array[$data_script_array_pointer]}"
			 				data_script_array_pointer=`expr $data_script_array_pointer + 1`
			 			done
			 			echo "q. Return to menu"
			 			echo -n ":>"
			 			read script_input
			 			echo $script_input | grep "[^0-9]" > /dev/null 2>&1
						if [ "$?" -eq "0" ]; then
							if [ "$script_input" == "q" ] || [ "$script_input" == "Q" ]; then
								echo "Exiting Script Selection Menu"
								menu_exit=1 #indicates user chose to exit Add instrument menu
								error_flag=1
								non_int_flag=1
								sleep 1
							else
								echo "Invalid Input"
								sleep 1
							fi
						else
							if [ "$script_input" -gt "$data_script_array_max" ]; then
								echo "Selection out of range"
								error_flag=1
								non_int_flag=1
								sleep 1
							else
								report_script="${data_script_array[$script_input]}"
								echo "script set to $report_script"
								sleep 1
							fi	
						fi
					done
				;;
					
				"6" )
					clear
					if [ "$report_name" = "" ] | [ "$report_month" = "" ] | [ "$report_year" = "" ] | [ "$report_email" = "" ]; then
						echo "Missing parameter. Please enter instrument name and month/year to process."
					else
						echo "generating report..."
						sleep 5
						command="./sys_resources/data_parser.sh $report_name $report_month $report_year $report_email $report_script &"
						echo "$command"
						eval $command
						wait $!
						echo "Report generated. The file $report_name-$report_month-$report_year.bz2 was sent to $report_email."
						sleep 5
   					fi	
				;;
				"q" | "Q" )
					echo "returning to main menu"
					r_to_main=1
					sleep 1
				;;
			
				* )
	   				echo "not a valid option"
					sleep 1
					;;
			esac
		done		
	;;

	"q" | "Q" )
		if [ "$1" = "log" ]; then
			DATE=$(date +%x-%T.%N)  ##DEBUGLOG##
			echo "**********$DATE***********" >> $logfile  ##DEBUGLOG##
			echo "in shutdown" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "./interface.sh" >> $logfile   ##DEBUGLOG##
			ps -fe | grep "testd" >> $logfile  ##DEBUGLOG##
		fi
		clear
		if [ "$datalogger_on" -eq 1 ]; then
			d_shutdown
			main_exit=1
			exit
		else
			main_exit=1
			exit
		fi
	;;

	* )
		echo "not a valid option"
		sleep 1
	;;
esac
done
exit
